package com.ben.tcptester.tcpclient.netty;

import com.ben.tcptester.bean.ws.EventMessage;
import com.ben.tcptester.bean.ws.EventType;
import com.ben.tcptester.bean.ws.WsBaseResponse;
import com.ben.tcptester.bean.ws.WsMsgType;
import com.ben.tcptester.util.JsonUtil;
import com.ben.tcptester.web.websocket.MyTextWebSocketHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import org.apache.log4j.Logger;
import org.springframework.web.socket.TextMessage;

/**
 * Created by Peter on 2017/6/30.
 */
public class UserHandler extends ChannelHandlerAdapter {
    private static Logger logger = Logger.getLogger(UserHandler.class);

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("连接激活 " + ctx.channel().remoteAddress().toString());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("断开连接 channelInactive --- " + ctx.channel().id().asLongText());
        Channel channel = ctx.channel();
        String clientId = channel.id().asLongText();

        // 通过WebSocket向界面推送连接断开的消息
        EventMessage eventMessage = new EventMessage(EventType.disconnect, clientId);
        WsBaseResponse message = new WsBaseResponse(WsMsgType.event, eventMessage);
        TextMessage textMessage = new TextMessage(JsonUtil.toJson(message));
        MyTextWebSocketHandler.sendMessageUser(textMessage,clientId);

        ServerRepository.removeClient(clientId);//从仓库中移除客户端连接对象
        logger.info("关闭连接成功");
    }

    @Override
    public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception {
        logger.info("断开连接 close --- " + ctx.channel().id().asLongText());
        super.close(ctx, promise);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String stringMessage = (String) msg;
        logger.info("read -->> ::" + msg);
        String clientId = ctx.channel().id().asLongText();
        WsBaseResponse message = new WsBaseResponse(WsMsgType.text, stringMessage);
        TextMessage textMessage = new TextMessage(JsonUtil.toJson(message));
        MyTextWebSocketHandler.sendMessageUser(textMessage,clientId);
    }
}
